# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        # 防止，删除变为空指针。
        _ = ListNode(0)
        _.next = head
        # 快慢指针。
        slow, fast = _, _
        # 快指针，后移n个节点。
        for i in range(n):
            fast = fast.next
        # 同时移动快慢指针。当快指针到末尾时，慢指针正好在倒数第n-1个节点位置。
        while (fast is not None) and (fast.next is not None):
            fast = fast.next
            slow = slow.next
        # 删除目标节点
        slow.next = slow.next.next
        return _.next
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
'''
如果不写_的话,输出的没有头节点? head就被删除掉了?所以真的开始不是head,开始的节点就是_,也就是空? 
'''
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        _=ListNode(0)#初始化一个节点为0的空节点,最后的时候删除就可以了
        _.next = head
        fast = _
        slow = _
        for i in range(n):
            fast = fast.next
        if not fast: return head.next
        while fast and fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return _.next
